package org.github.latex;


import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.*;

public class ExternalProgram {

    private final static ExecutorService executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2 );

    static {
        Runtime.getRuntime().addShutdownHook(new Thread(){
            @Override
            public void run() {
                executorService.shutdown();
            }
        });
    }

    private String cmd ;

    private File workDir;

    public ExternalProgram(String cmd , File workDir){
        this.cmd = cmd;
        this.workDir = workDir;
    }



    public String run() throws IOException {

        final Process process = Runtime.getRuntime().exec(cmd, null, workDir);

        Future<String> outputFuture = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return IOUtils.toString(process.getInputStream() ,"utf-8");
            }
        });

        Future<String> errorOutputFuture = executorService.submit(new Callable<String>() {
            @Override
            public String call() throws Exception {
                return IOUtils.toString(process.getErrorStream() ,"utf-8");
            }
        });

        String output = null;
        try {
            output = outputFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }
        String errorOutput = null;
        try {
            errorOutput = errorOutputFuture.get();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (ExecutionException e) {
            e.printStackTrace();
        }

        if(StringUtils.isNotEmpty(errorOutput)){
            output =  output + "#error#" +  errorOutput;
        }

        return output;
    }

}
